/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: uds_transport.c
 *
 * Purpose: implementation implementation unix domain socket transport(dialer and listener) ops for cbus
 *
 * Developer:
 *   wen.gu , 2022-02-16
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#ifdef LINUX_ENABLE_TRANSPORT_IPC
#include "uds_transport.h"

#include "cbus/core/cbus_log.h"
/******************************************************************************
 **    MACROS
 ******************************************************************************/

/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

/******************************************************************************
 **    inner FUNCTION DEFINITIONS
 ******************************************************************************/


/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/


/**
 * @brief destroy a pipe instance
 * @param handle [in] a instance of pipe
 * @return GErrc, success: G_OK, else error code.
 * 
 */
GErrc uds_pipe_finish(GPHD handle)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    socket_t socket_id = (socket_t)handle;

    if (socket_id != INVALID_SOCKET)
    {
        close(socket_id);
    }
    return G_OK;
}

/**
 * @brief send data to remote side
 * @param handle [in] the isntance handle of pipe
 * @param buf [in] data buffer
 * @param len [in] data length
 * @return G_OK: success, else: failed @see GErrc 
 * 
 */
GErrc uds_pipe_send(GPHD handle, GBUF buf, GU32 len)
{
    if (!handle || !buf || (len == 0))
    {
        return G_ErrBadParameter;
    }

    socket_t socket_id = (socket_t)handle;

    while (len > 0)
    {
        int32_t ret_len = send(socket_id, (char*)buf, len, 0);
        if (ret_len > 0)
        {
            len -= ret_len;
            buf += ret_len;
        }
        else if (ret_len == 0)
        {
            return G_ErrDisconnected;
        }
        else
        {
            if (errno != EINTR)
            {
                return G_ErrDisconnected;
            }
            /** todo something */
        }
    } 

    return G_OK;
}

/**
 * @brief receive data from remote side
 * @param handle [in] the isntance handle of pipe
 * @param buf [in] the data buffer to storage received data
 * @param buf_size [in] the size of data buffer(indicat max receive size)
 * @param timeout_ms [in] how many time to wait receive. if receive nothing in 'timeout_ms', then return G_ErrTimeout, 
 *                        CBUS_TRANSPORT_RECEIVE_WAIT_FOREVER for wait forever
 * @return > 0 : receive data size, else(<= 0): error code @see GErrc
 * 
 */

GS32 uds_pipe_recv(GPHD handle, GBUF buf, GU32 buf_size, GU32 timeout_ms)
{
    if (!handle || !buf || (buf_size == 0))
    {
        return (GS32)G_ErrBadParameter;
    }

    fd_set read_set;
    int ret = 0;
     
    
    socket_t socket_id = (socket_t)handle; 

    FD_ZERO(&read_set);        
    FD_SET(socket_id, &read_set);
    
    //LOGD("[%s.%d]===>:\n", __FUNCTION__, __LINE__);

    if (CBUS_TRANSPORT_RECEIVE_WAIT_FOREVER == timeout_ms)
    {
        ret = select(socket_id + 1, &read_set, NULL, NULL, NULL);
    }
    else
    {
        struct timeval select_timeout = {0};  //timeout time   
        select_timeout.tv_sec = timeout_ms / 1000;   /** */
        select_timeout.tv_usec = (timeout_ms % 1000) * 1000;
        ret = select(socket_id + 1, &read_set, NULL, NULL, &select_timeout);
    }    

    //LOGD("[%s.%d]===>:ret:%d, max_fd:%lld\n", __FUNCTION__, __LINE__, ret, socket_id);

    if ((ret > 0) && FD_ISSET(socket_id, &read_set))
    {        
        GS32 len = read(socket_id, buf, buf_size);
        //LOGD("[%s.%d]===>: read data len: %d\n", __FUNCTION__, __LINE__, len);
        if (len > 0)
        {
            
            return len;
        }
        else if (len == 0)
        {
            return G_ErrDisconnected;
        }
        else
        {
            if (errno != EINTR)
            {
                LOGE("read error: %s\n", strerror(errno));
                return G_ErrDisconnected;
            }
            else
            {
                return (GS32)G_ErrInterrupted;
                //LOGE("read error: %s\n", strerror(errno));
            }
        }            
    }
    else if (ret == 0)
    {
        return (GS32)G_ErrTimeout;
    }

    return (GS32)G_ErrUndefined;
}


/**
 * @brief if not NULL, is called once during library initialization
 * @param none
 * @return GErrc, success: G_OK, else error code.
 * 
*/
GErrc uds_transport_initialize()
{
    return G_OK;
}

/**
 * @brief if not NULL, is called during library deinitialization,
 *        It should release any global resources, close any open files, etc.
 * @param none
 * @return GErrc, success: G_OK, else error code.
 * 
 */
GErrc uds_transport_finish()
{
    return G_OK;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////

static const cbus_dialer_ops g_uds_dialer_ops = 
{
    uds_dialer_initialize,
    uds_dialer_finish,
    uds_dialer_connect,
};

static const cbus_listener_ops g_uds_listener_ops = 
{
    uds_listener_initialize,
    uds_listener_finish,
    uds_listener_bind,
    uds_listener_unbind,
    uds_listener_accept,
};

static const cbus_pipe_ops g_uds_pipe_ops = 
{
    uds_pipe_finish,
    uds_pipe_send,
    uds_pipe_recv,
};

static const cbus_transport_ops g_uds_trans_ops = 
{
    CBUS_TRANSPORT_VERSION,
    "ipc",
    uds_transport_initialize,
    uds_transport_finish,
    &g_uds_dialer_ops,
    &g_uds_listener_ops,
    &g_uds_pipe_ops
};


GErrc cbus_uds_transport_default_ctor(void)
{
    return cbus_transport_register(&g_uds_trans_ops);
}

#endif /** end of LINUX_ENABLE_TRANSPORT_IPC */